<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Manage extends CI_Controller {

    public function index() {

        $this->wechat_list();
    }

    /*     * ***************************************视频管理********************************************************** */

    public function wechat_list() {
        $data['menu'] = "manage_wechat";


        //获取所有分类的列表
        $data["type_list"] = fetch_array("SELECT * FROM type");


        //名称搜索
        $data['s_name'] = getGP("s_name");
        $data['s_name_type'] = getGP("s_name_type") ;
        $data['s_name_type'] = !empty($data['s_name_type']) ? $data['s_name_type'] : 1;
        //筛选搜索
        $data['s_price'] = getGP("s_price");
        $data['s_price'] = !empty($data['s_price']) ? $data['s_price'] : 1;
        $data['s_price_start'] = intval(getGP("s_price_start"));
        $data['s_price_end'] = intval(getGP("s_price_end"));
        $data['s_fans'] = getGP("s_fans");
        $data['s_fans'] = !empty($data['s_fans']) ? $data['s_fans'] : 1;
        $data['s_fans_start'] = intval(getGP("s_fans_start"));
        $data['s_fans_end'] = intval(getGP("s_fans_end"));
        $data['s_type_ids'] = empty($_GET["s_type_ids"]) ? array() : $_GET["s_type_ids"];


        //导出动作的参数
        $data['isexport'] = getGP("isexport");
        $data['ids'] = getGP("ids");

        $where = " WHERE 1 ";


        //如果已经指定了账号的id列表，则直接使用ids作为搜索条件
        
        if (!empty($data['ids'])) {
            $sql = "SELECT * FROM wechat WHERE id IN ({$data['ids']}) ";
        } else {
            //名称筛选
//            if (!empty($data['s_name'])) {
                //账号名称搜索
                if ($data['s_name_type'] == 1) {
                    $where .=" and ( w.account_name like '%{$data['s_name']}%')";
                }
                //供应商编号搜索
                else {
                    $where .=" and ( w.code like '%{$data['s_name']}%')";
                }
//                $data['s_price'] = 1;
//                $data['s_price_start'] = 0;
//                $data['s_price_end'] = 0;
//                $data['s_fans'] = 1;
//                $data['s_fans_start'] = 0;
//                $data['s_fans_end'] = 0;
//                $data['s_type_ids'] = array();
//            }
            //条件筛选
//            else {
                //价格筛选
                if ($data['s_price'] == 2) {
                    $where .=" and ( w.price1 between {$data['s_price_start']} AND {$data['s_price_end']})";
                }
                //粉丝数筛选
                if ($data['s_fans'] == 2) {
                    $where .=" and ( w.fans between {$data['s_fans_start']} AND {$data['s_fans_end']})";
                }
                //分类筛选
                if (!empty($data['s_type_ids'])) {
                    $s_type_ids = implode(",", $data['s_type_ids']);
                    $where .=" and (wt.type_id IN ({$s_type_ids}))";
                }
//                $data['s_name'] = "";
//                $data['s_name_type'] = 1;
//            }
            $sql = "SELECT w.* FROM wechat_type wt"
                    . " LEFT JOIN wechat w ON  wt.wechat_id = w.id "
                    . " $where GROUP BY w.id";
        }
        
        //////////////////////显示列表//////////////////////
        if ($data['isexport'] != 2) {
            //分页配置1
            $per_page = getGP('per_page') ? getGP('per_page') : 1;
            $config['per_page'] = 200; //每一页显示行数
            $config['base_url'] = "index.php?c=manage&m=wechat_list&s_name={$data['s_name']}" .
                    "&s_name_type={$data['s_name_type']}" .
                    "&s_price={$data['s_price']}" .
                    "&s_price_start={$data['s_price_start']}" .
                    "&s_price_end={$data['s_price_end']}" .
                    "&s_fans={$data['s_fans']}" .
                    "&s_fans_start={$data['s_fans_start']}" .
                    "&s_fans_end={$data['s_fans_end']}";
            if (!empty($data["s_type_ids"])) {
                foreach ($data["s_type_ids"] as $k => $v) {
                    $config['base_url'].="&s_type_ids%5B%5D=$v";
                }
            }
            $limit = $config['per_page'];
            $start = ($per_page - 1) * $limit;
            //分页配置2
            $data['count'] = $count = fetch_count($sql);
            $config['total_rows'] = $count;
            //根据组装的sql语句查询数据库
            $res = fetch_array($sql . " ORDER BY w.edittime DESC  LIMIT $start,$limit");
            //获取每个账号的所属分类
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    $tmp = fetch_array("SELECT t.* FROM wechat_type wt"
                            . " LEFT JOIN type t ON  wt.type_id = t.id "
                            . "WHERE wt.wechat_id = " . $v["id"]);
                    $tmp_type = array();
                    foreach ($tmp as $vv) {
                        $tmp_type[] = $vv["type_name"];
                    }
                    $res[$k]["type_name"] = implode("|", $tmp_type);
                }
            }
            $data['res'] = $res;
            $this->pagination->initialize($config);
            $page = $this->pagination->create_links();
            $data['pager'] = $page;
            $this->load->view('wechat_list', $data);
        }
        /////////////////导出动作///////////////////////////////////
        else {
            
            $res = fetch_array($sql . " ORDER BY edittime ASC");
            $data['count'] = fetch_count($sql);
            //获取每个账号的所属分类
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    $tmp = fetch_array("SELECT t.* FROM wechat_type wt"
                            . " LEFT JOIN type t ON  wt.type_id = t.id "
                            . "WHERE wt.wechat_id = " . $v["id"]);
                    $tmp_type = array();
                    foreach ($tmp as $vv) {
                        $tmp_type[] = $vv["type_name"];
                    }
                    $res[$k]["type_name"] = implode("|", $tmp_type);
                }
            }
            $data['res'] = $res;
            $content = $this->load->view('wechat_export', $data, true);
            
            user_log_save($_SESSION["username"],$_SESSION["userid"],"导出".$data['count']."个视频账号");
            header("Content-type:application/vnd.ms-excel;charset:utf8");
            header("Content-Disposition:filename=" . "wechat" . date("YmdHis") . ".xls");
            echo $content;
        }
    }

    public function wechat_add() {
        $data['menu'] = "manage_wechat";
        $data['type_list'] = fetch_array("select * from type");
        $this->load->view('wechat_add', $data);
    }

    public function wechat_edit() {
        $data['menu'] = "manage_wechat";
        $id = getGP('id');
        $sql = "select * from wechat where id='" . $id . "'";
        $res = fetch_one_array($sql);

        //获取该账号所属类别
        $tmp = fetch_array("SELECT t.* FROM wechat_type wt"
                . " LEFT JOIN type t ON  wt.type_id = t.id "
                . "WHERE wt.wechat_id = " . $res["id"]);
        if (!empty($tmp)) {
            foreach ($tmp as $vv) {
                $res["type_ids"][] = $vv["id"];
            }
        } else {
            $res["type_ids"] = array();
        }
        $data['res'] = $res;
        $data['type_list'] = fetch_array("select * from type");
        $this->load->view('wechat_edit', $data);
    }

    public function wechat_save() {
        $data['menu'] = "manage_wechat";
        $ins_data['account_name'] = getGP('account_name');//账号名字
        // $ins_data['wechat_name'] = getGP('wechat_name');
        $ins_data['description'] = getGP('description');//简介
        // $ins_data['fans'] = getGP('fans');
        // $ins_data['link'] = getGP('link');
        // $ins_data['price1'] = getGP('price1');
        // $ins_data['price2'] = getGP('price2');
        // $ins_data['read_count'] = getGP('read_count');
        // $ins_data['code'] = getGP('code');
        $ins_data['ps'] = getGP('ps');//合作须知
        $ins_data['display_order'] = getGP('display_order');//显示顺序
        // shuai180806
        $ins_data['address'] = getGP('address');//地址
        $ins_data['case'] = getGP('case');//案例
        $ins_data['original_price'] = getGP('original_price');//原创直发
        $ins_data['contact'] = getGP('contact');//联系方式

        $ins_data['id'] = getGP('id'); 
        $type_ids = $_POST['type_ids'];//类型    
        // var_dump("输出type_ids");
        // var_dump($type_ids);
        // exit();
       
        //图片上传
        $config['upload_path']='./uploads/';
        $config['allowed_types']='gif|jpg|png';
        $config['max_size']=5120;
        $config['encrypt_name']=true;
        // $config['max_width']=1024;
        // $config['max_height']=1024;
        $file_name = null;

        $this->load->library('upload',$config);
        if(!$this->upload->do_upload('head_img')){
            $error=array('error'=>$this->upload->display_errors());
            var_dump($error);
            if(!empty($ins_data['id'])){//说明是修改资料
                var_dump("有id是".$ins_data['id']);   
                $query = $this->db->query('SELECT head_img FROM wechat WHERE id = '.$ins_data['id']);
                // var_dump($query->result());
                $ins_data['head_img'] = $query->result()[0]->head_img;
                // exit();
            }else{ 
                alert("头像上传失败,图片（gif/jpg/png）不要超过5M");
            } 
        }else{
            $data=array('upload_data'=>$this->upload->data());
            // var_dump($data);
            $file_name = $data["upload_data"]["file_name"];
            $ins_data['head_img'] = "http://".$_SERVER['SERVER_NAME']."/uploads/".$file_name;
        }
        
        // $path_info = $_SERVER['SERVER_NAME'];
        // var_dump($path_info);
        // var_dump($_SERVER["HTTP_REFERER"]);
        // var_dump($_SERVER['REQUEST_URI']);
        // var_dump($_SERVER['HTTP_HOST']);
        // var_dump($_SERVER['SERVER_PORT']);

        if (empty($type_ids)) {
            alert("请选择所属类别");
        }

        $id = 0;

        if (!empty($ins_data['id'])) {//有id说明是修改资料
            $ins_data["edittime"] = time();
            var_dump($ins_data);
            $r = $this->db->update('wechat', $ins_data, "id =" . $ins_data['id']);
            $id = $ins_data['id'];
        } else {//新增成员
            $ins_data["addtime"] = time();
            $ins_data["edittime"] = time();
            $this->db->insert('wechat', $ins_data);
            $id = $this->db->insert_id();
        }
        
        if (!empty($id)) {
            //修改所属类别
            //先删除
            $sql = "delete from wechat_type where wechat_id='" . $id . "'";
            $r = $this->db->query($sql);
            foreach ($type_ids as $type_id) {
                $this->db->insert("wechat_type", array("wechat_id" => $id, "type_id" => $type_id));
            }
            user_log_save($_SESSION["username"],$_SESSION["userid"],"新增或编辑视频账号\"".$ins_data['account_name']."\"");
            alert("保存成功", "index.php?c=manage&m=wechat_list");
        } else {
            alert("保存失败");
        }
    }

    public function wechat_delete() {
        $data['menu'] = "manage_wechat";
        $id = intval(getGP('id'));
        $del_ids = getGP("del_ids"); 
        if(empty($id)&&empty($del_ids)){
            alert("缺少ID", "index.php?c=manage&m=wechat_list");
        }
        $ids_string = !empty($del_ids)?$del_ids:$id;

        $sql = "delete from wechat where id IN(" . $ids_string . ")";
        $r = $this->db->query($sql);
        $sql = "delete from wechat_type where wechat_id IN(" . $ids_string . ")";
        $r = $this->db->query($sql);

        if ($r) {
            user_log_save($_SESSION["username"],$_SESSION["userid"],"删除了视频id为".$ids_string."账号");
            alert("删除成功", "index.php?c=manage&m=wechat_list");
        } else {
            alert("删除失败", "index.php?c=manage&m=wechat_list");
        }
        
        
    }

    //视频账号导入
    public function wechat_import() {
        ini_set('max_execution_time', '0');
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'csv|txt';
        $config['max_size'] = '1000000';
        $this->load->library('upload', $config);
        if (empty($_FILES["userfile"]["tmp_name"])) {
            alert("请选择上传的文件");
        }
        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            alert($error["error"]);
            die;
        } else {
            $data = array('upload_data' => $this->upload->data());

            //先读取内容并转成UTF-8编码，再重新写入
            file_put_contents($data['upload_data']['full_path'], mb_convert_encoding(file_get_contents($data['upload_data']['full_path']), "UTF-8", "GBK"));
            //重新用fgetcsv读取csv内容
            $h = fopen($data['upload_data']['full_path'], "r");
            $i = 0;
            $count =0;
            while ($tmp = _fgetcsv($h)) {
                $i++;
                if ($i == 1) {
                    continue;
                }
                if (!empty($tmp[0])) {
                    $ins_data['account_name'] = $tmp[1];
                    $ins_data['description'] = $tmp[2];
                    $ins_data['address'] = $tmp[3];
                    $ins_data['case'] = $tmp[4];
                    $ins_data['original_price'] = $tmp[5];
                    $ins_data['ps'] = $tmp[6];
                    $ins_data['contact'] = $tmp[7];

                    // $ins_data['wechat_name'] = $tmp[3];
                    // $ins_data['fans'] = $tmp[2];
//                $ins_data['link'] = $tmp[2];
                    // $ins_data['price1'] = $tmp[4];
                    // $ins_data['price2'] = $tmp[5];
//                $ins_data['price3'] = $tmp[2];
                    // $ins_data['read_count'] = $tmp[6];
                    // $ins_data['code'] = $tmp[9];
                    // $ins_data['ps'] = $tmp[8];
                    // $ins_data['display_order'] = 0;
//                $ins_data['type_id'] = getGP('type_id');
//                $ins_data['type_name'] = getGP('type_name');

                    $ins_data["addtime"] = time();
                    $ins_data["edittime"] = time();
                    $this->db->insert('wechat', $ins_data);
                    $wechat_id = $this->db->insert_id();
                    if (!empty($wechat_id)) {
                        $count++;
                        if (!empty($tmp[0])) {
                            $types = explode("|", $tmp[0]);
                            foreach ($types as $type) {
                                $type_data = fetch_one_array("SELECT * FROM type WHERE type_name='" . $type . "'");
                                if (empty($type_data)) {
                                    $type_id = $this->db->insert('type', array("type_name" => $type));
                                } else {
                                    $type_id = $type_data['id'];
                                }
                                $this->db->insert("wechat_type", array("wechat_id" => $wechat_id, "type_id" => $type_id));
                            }
                        }
                    } else {
                        alert("第" . $i . "条数据添加失败,请检查后重新导入");
                        break;
                    }
                }
            }
            user_log_save($_SESSION["username"],$_SESSION["userid"],"导入文件，共添加了".$count."个视频账号");
            alert("导入成功！","index.php?c=manage&m=wechat_list");
        }
    }

   

    /*     * ***************************************漫画管理********************************************************** */

    public function weibo_list() {
        $data['menu'] = "manage_weibo";

        //获取所有分类的列表
        $data["type_list"] = fetch_array("SELECT * FROM type");

        //名称搜索
        $data['s_name'] = getGP("s_name");
        $data['s_name_type'] = getGP("s_name_type") ;
        $data['s_name_type'] = !empty($data['s_name_type']) ? $data['s_name_type'] : 1;
        
        //筛选搜索
        $data['s_price'] = getGP("s_price");
        $data['s_price'] = !empty($data['s_price']) ? $data['s_price'] : 1;
        $data['s_price_start'] = intval(getGP("s_price_start"));
        $data['s_price_end'] = intval(getGP("s_price_end"));
        $data['s_fans'] = getGP("s_fans");
        $data['s_fans'] = !empty($data['s_fans']) ? $data['s_fans'] : 1;
        $data['s_fans_start'] = intval(getGP("s_fans_start"));
        $data['s_fans_end'] = intval(getGP("s_fans_end"));
        $data['s_type_ids'] = empty($_GET["s_type_ids"]) ? array() : $_GET["s_type_ids"];


        //导出动作的参数
        $data['isexport'] = getGP("isexport");
        $data['ids'] = getGP("ids");

        $where = " WHERE 1 ";


        //如果已经指定了账号的id列表，则直接使用ids作为搜索条件
        if (!empty($data['ids'])) {
            $sql = "SELECT * FROM weibo WHERE id IN ({$data['ids']}) ";
        } else {
            //名称筛选
//            if (!empty($data['s_name'])) {
                //账号名称搜索
                if ($data['s_name_type'] == 1) {
                    $where .=" and ( w.account_name like '%{$data['s_name']}%')";
                }
                //供应商编号搜索
                else {
                    $where .=" and ( w.code like '%{$data['s_name']}%')";
                }
//                $data['s_price'] = 1;
//                $data['s_price_start'] = 0;
//                $data['s_price_end'] = 0;
//                $data['s_fans'] = 1;
//                $data['s_fans_start'] = 0;
//                $data['s_fans_end'] = 0;
//                $data['s_type_ids'] = array();
//            }
            //条件筛选
//            else {
                //价格筛选
                if ($data['s_price'] == 2) {
                    $where .=" and ( w.price1 between {$data['s_price_start']} AND {$data['s_price_end']})";
                }
                //粉丝数筛选
                if ($data['s_fans'] == 2) {
                    $where .=" and ( w.fans between {$data['s_fans_start']} AND {$data['s_fans_end']})";
                }
                //分类筛选
                if (!empty($data['s_type_ids'])) {
                    $s_type_ids = implode(",", $data['s_type_ids']);
                    $where .=" and (wt.type_id IN ({$s_type_ids}))";
                }
//                $data['s_name'] = "";
//                $data['s_name_type'] = 1;
//            }
            $sql = "SELECT w.* FROM weibo_type wt"
                    . " LEFT JOIN weibo w ON  wt.weibo_id = w.id "
                    . " $where GROUP BY w.id";
        }
        //////////////////////显示列表//////////////////////
        if ($data['isexport'] != 2) {
            //分页配置1
            $per_page = getGP('per_page') ? getGP('per_page') : 1;
            $config['per_page'] = 200; //每一页显示行数
            $config['base_url'] = "index.php?c=manage&m=weibo_list&s_name={$data['s_name']}" .
                    "&s_name_type={$data['s_name_type']}" .
                    "&s_price={$data['s_price']}" .
                    "&s_price_start={$data['s_price_start']}" .
                    "&s_price_end={$data['s_price_end']}" .
                    "&s_fans={$data['s_fans']}" .
                    "&s_fans_start={$data['s_fans_start']}" .
                    "&s_fans_end={$data['s_fans_end']}";
            if (!empty($data["s_type_ids"])) {
                foreach ($data["s_type_ids"] as $k => $v) {
                    $config['base_url'].="&s_type_ids%5B%5D=$v";
                }
            }
            $limit = $config['per_page'];
            $start = ($per_page - 1) * $limit;
            //分页配置2
            $data['count'] = $count = fetch_count($sql);
            $config['total_rows'] = $count;
            $res = fetch_array($sql . " ORDER BY w.edittime DESC  LIMIT $start,$limit");
            //获取每个账号的所属分类
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    $tmp = fetch_array("SELECT t.* FROM weibo_type wt"
                            . " LEFT JOIN type t ON  wt.type_id = t.id "
                            . "WHERE wt.weibo_id = " . $v["id"]);
                    $tmp_type = array();
                    foreach ($tmp as $vv) {
                        $tmp_type[] = $vv["type_name"];
                    }
                    $res[$k]["type_name"] = implode("|", $tmp_type);
                }
            }
            $data['res'] = $res;
            $this->pagination->initialize($config);
            $page = $this->pagination->create_links();
            $data['pager'] = $page;
            $this->load->view('weibo_list', $data);
        }
        /////////////////导出动作///////////////////////////////////
        else {
            $res = fetch_array($sql . " ORDER BY edittime ASC");
            $data['count'] = fetch_count($sql);
            //获取每个账号的所属分类
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    $tmp = fetch_array("SELECT t.* FROM weibo_type wt"
                            . " LEFT JOIN type t ON  wt.type_id = t.id "
                            . "WHERE wt.weibo_id = " . $v["id"]);
                    $tmp_type = array();
                    foreach ($tmp as $vv) {
                        $tmp_type[] = $vv["type_name"];
                    }
                    $res[$k]["type_name"] = implode("|", $tmp_type);
                }
            }
            $data['res'] = $res;
            $content = $this->load->view('weibo_export', $data, true);
            
            user_log_save($_SESSION["username"],$_SESSION["userid"],"导出".$data['count']."个漫画账号");
            
            header("Content-type:application/vnd.ms-excel;charset:utf8");
            header("Content-Disposition:filename=" . "weibo" . date("YmdHis") . ".xls");
            echo $content;
        }
    }

    public function weibo_add() {
        $data['menu'] = "manage_weibo";
        $data['type_list'] = fetch_array("select * from type");
        $this->load->view('weibo_add', $data);
    }

    public function weibo_edit() {
        $data['menu'] = "manage_weibo";
        $id = getGP('id');
        $sql = "select * from weibo where id='" . $id . "'";
        $res = fetch_one_array($sql);
        //获取该账号所属类别
        $tmp = fetch_array("SELECT t.* FROM weibo_type wt"
                . " LEFT JOIN type t ON  wt.type_id = t.id "
                . "WHERE wt.weibo_id = " . $res["id"]);
        if (!empty($tmp)) {
            foreach ($tmp as $vv) {
                $res["type_ids"][] = $vv["id"];
            }
        } else {
            $res["type_ids"] = array();
        }
        $data['res'] = $res;

        $data['type_list'] = fetch_array("select * from type");
        $this->load->view('weibo_edit', $data);
    }

    public function weibo_save() {
        $data['menu'] = "manage_weibo";
        $ins_data['account_name'] = getGP('account_name');
        $ins_data['description'] = getGP('description');
        // $ins_data['fans'] = getGP('fans');
        // $ins_data['link'] = getGP('link');
        // $ins_data['price1'] = getGP('price1');
        // $ins_data['price2'] = getGP('price2');
//        $ins_data['price3'] = getGP('price3');
        // $ins_data['code'] = getGP('code');
        $ins_data['ps'] = getGP('ps');
        $ins_data['display_order'] = getGP('display_order');
        // shuai180806
        $ins_data['address'] = getGP('address');//地址
        $ins_data['case'] = getGP('case');//案例
        $ins_data['original_price'] = getGP('original_price');//原创直发
        $ins_data['contact'] = getGP('contact');//联系方式
        $ins_data['id'] = getGP('id');
        $type_ids = $_POST['type_ids'];

        //图片上传
        $config['upload_path']='./uploads/';
        $config['allowed_types']='gif|jpg|png';
        $config['max_size']=5120;
        $config['encrypt_name']=true;
        $file_name = null;
        $this->load->library('upload',$config);
        if(!$this->upload->do_upload('head_img')){
            $error=array('error'=>$this->upload->display_errors());
            var_dump($error);
            if(!empty($ins_data['id'])){//说明是修改资料
                var_dump("有id是".$ins_data['id']);   
                $query = $this->db->query('SELECT head_img FROM weibo WHERE id = '.$ins_data['id']);
                $ins_data['head_img'] = $query->result()[0]->head_img;
            }else{ 
                alert("头像上传失败,图片（gif/jpg/png）不要超过5M");
            } 
        }else{
            $data=array('upload_data'=>$this->upload->data());
            $file_name = $data["upload_data"]["file_name"];
            $ins_data['head_img'] = "http://".$_SERVER['SERVER_NAME']."/uploads/".$file_name;
        }


        if (empty($type_ids)) {
            alert("请选择所属类别");
        }

        $id = 0;

        if (!empty($ins_data['id'])) {
            $ins_data["edittime"] = time();
            $r = $this->db->update('weibo', $ins_data, "id =" . $ins_data['id']);
            $id = $ins_data['id'];
        } else {
            $ins_data["addtime"] = time();
            $ins_data["edittime"] = time();
            $this->db->insert('weibo', $ins_data);
            $id = $this->db->insert_id();
        }

        if (!empty($id)) {
            //修改所属类别
            //先删除
            $sql = "delete from weibo_type where weibo_id='" . $id . "'";
            $r = $this->db->query($sql);
            foreach ($type_ids as $type_id) {
                $this->db->insert("weibo_type", array("weibo_id" => $id, "type_id" => $type_id));
            }
            user_log_save($_SESSION["username"],$_SESSION["userid"],"新增或编辑漫画账号\"".$ins_data['account_name']."\"");
            alert("保存成功", "index.php?c=manage&m=weibo_list");
        } else {
            alert("保存失败");
        }
    }

    public function weibo_delete() {
        $data['menu'] = "manage_weibo";
        $id = intval(getGP('id'));
        $del_ids = getGP("del_ids");  
        if(empty($id)&&empty($del_ids)){
            alert("缺少ID", "index.php?c=manage&m=weibo_list");
        }
        $ids_string = !empty($del_ids)?$del_ids:$id;

        $sql = "delete from weibo where id IN(" . $ids_string . ")";
        $r = $this->db->query($sql);
        $sql = "delete from weibo_type where weibo_id IN(" . $ids_string . ")";
        $r = $this->db->query($sql);

        if ($r) {
            user_log_save($_SESSION["username"],$_SESSION["userid"],"删除了漫画id为".$ids_string."账号");
            alert("删除成功", "index.php?c=manage&m=weibo_list");
        } else {
            alert("删除失败", "index.php?c=manage&m=weibo_list");
        }
    }

    //漫画导入
    public function weibo_import() {
        ini_set('max_execution_time', '0');
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'csv|txt';
        $config['max_size'] = '1000000';
        $this->load->library('upload', $config);
        if (empty($_FILES["userfile"]["tmp_name"])) {
            alert("请选择上传的文件");
        }
        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            alert($error["error"]);
            die;
        } else {
            $data = array('upload_data' => $this->upload->data());

            //先读取内容并转成UTF-8编码，再重新写入
            file_put_contents($data['upload_data']['full_path'], mb_convert_encoding(file_get_contents($data['upload_data']['full_path']), "UTF-8", "GBK"));
            //重新用fgetcsv读取csv内容
            $h = fopen($data['upload_data']['full_path'], "r");
            $i = 0;
            $count=0;
            while ($tmp = _fgetcsv($h)) {
                $i++;
                if ($i == 1) {
                    continue;
                }

                if (!empty($tmp[0])) {
                    $ins_data['account_name'] = $tmp[1];
                    $ins_data['description'] = $tmp[2];
                    $ins_data['address'] = $tmp[3];
                    $ins_data['case'] = $tmp[4];
                    $ins_data['original_price'] = $tmp[5];
                    $ins_data['ps'] = $tmp[6];
                    $ins_data['contact'] = $tmp[7];


                    $ins_data["addtime"] = time();
                    $ins_data["edittime"] = time();
                    $this->db->insert('weibo', $ins_data);
                    $weibo_id = $this->db->insert_id();
                    if (!empty($weibo_id)) {
                        $count++;
                        if (!empty($tmp[0])) {
                            $types = explode("|", $tmp[0]);
                            foreach ($types as $type) {
                                $type_data = fetch_one_array("SELECT * FROM type WHERE type_name='" . $type . "'");
                                if (empty($type_data)) {
                                    $type_id = $this->db->insert('type', array("type_name" => $type));
                                } else {
                                    $type_id = $type_data['id'];
                                }
                                $this->db->insert("weibo_type", array("weibo_id" => $weibo_id, "type_id" => $type_id));
                            }
                        }
                    } else {
                        alert("第" . $i . "条数据添加失败,请检查后重新导入");
                        break;
                    }
                }
            }
            user_log_save($_SESSION["username"],$_SESSION["userid"],"导入文件，共添加了".$count."个漫画账号");
            alert("导入成功！","index.php?c=manage&m=weibo_list");
        }
    }

    /*********************************** 其他账户***************************/ 
    public function other_list() {
        $data['menu'] = "manage_other";

        //获取所有分类的列表
        $data["type_list"] = fetch_array("SELECT * FROM type");

        //名称搜索
        $data['s_name'] = getGP("s_name");
        $data['s_name_type'] = getGP("s_name_type") ;
        $data['s_name_type'] = !empty($data['s_name_type']) ? $data['s_name_type'] : 1;
        
        //筛选搜索
        $data['s_price'] = getGP("s_price");
        $data['s_price'] = !empty($data['s_price']) ? $data['s_price'] : 1;
        $data['s_price_start'] = intval(getGP("s_price_start"));
        $data['s_price_end'] = intval(getGP("s_price_end"));
        $data['s_fans'] = getGP("s_fans");
        $data['s_fans'] = !empty($data['s_fans']) ? $data['s_fans'] : 1;
        $data['s_fans_start'] = intval(getGP("s_fans_start"));
        $data['s_fans_end'] = intval(getGP("s_fans_end"));
        $data['s_type_ids'] = empty($_GET["s_type_ids"]) ? array() : $_GET["s_type_ids"];


        //导出动作的参数
        $data['isexport'] = getGP("isexport");
        $data['ids'] = getGP("ids");

        $where = " WHERE 1 ";


        //如果已经指定了账号的id列表，则直接使用ids作为搜索条件
        if (!empty($data['ids'])) {
            $sql = "SELECT * FROM other WHERE id IN ({$data['ids']}) ";
        } else {
            //名称筛选
//            if (!empty($data['s_name'])) {
                //账号名称搜索
                if ($data['s_name_type'] == 1) {
                    $where .=" and ( w.account_name like '%{$data['s_name']}%')";
                }
                //供应商编号搜索
                else {
                    $where .=" and ( w.code like '%{$data['s_name']}%')";
                }
//                $data['s_price'] = 1;
//                $data['s_price_start'] = 0;
//                $data['s_price_end'] = 0;
//                $data['s_fans'] = 1;
//                $data['s_fans_start'] = 0;
//                $data['s_fans_end'] = 0;
//                $data['s_type_ids'] = array();
//            }
            //条件筛选
//            else {
                //价格筛选
                if ($data['s_price'] == 2) {
                    $where .=" and ( w.price1 between {$data['s_price_start']} AND {$data['s_price_end']})";
                }
                //粉丝数筛选
                if ($data['s_fans'] == 2) {
                    $where .=" and ( w.fans between {$data['s_fans_start']} AND {$data['s_fans_end']})";
                }
                //分类筛选
                if (!empty($data['s_type_ids'])) {
                    $s_type_ids = implode(",", $data['s_type_ids']);
                    $where .=" and (wt.type_id IN ({$s_type_ids}))";
                }
//                $data['s_name'] = "";
//                $data['s_name_type'] = 1;
//            }
            $sql = "SELECT w.* FROM other_type wt"
                    . " LEFT JOIN other w ON  wt.other_id = w.id "
                    . " $where GROUP BY w.id";
        }
        //////////////////////显示列表//////////////////////
        if ($data['isexport'] != 2) {
            //分页配置1
            $per_page = getGP('per_page') ? getGP('per_page') : 1;
            $config['per_page'] = 200; //每一页显示行数
            $config['base_url'] = "index.php?c=manage&m=other_list&s_name={$data['s_name']}" .
                    "&s_name_type={$data['s_name_type']}" .
                    "&s_price={$data['s_price']}" .
                    "&s_price_start={$data['s_price_start']}" .
                    "&s_price_end={$data['s_price_end']}" .
                    "&s_fans={$data['s_fans']}" .
                    "&s_fans_start={$data['s_fans_start']}" .
                    "&s_fans_end={$data['s_fans_end']}";
            if (!empty($data["s_type_ids"])) {
                foreach ($data["s_type_ids"] as $k => $v) {
                    $config['base_url'].="&s_type_ids%5B%5D=$v";
                }
            }
            $limit = $config['per_page'];
            $start = ($per_page - 1) * $limit;
            //分页配置2
            $data['count'] = $count = fetch_count($sql);
            $config['total_rows'] = $count;
            $res = fetch_array($sql . " ORDER BY w.edittime DESC  LIMIT $start,$limit");
            //获取每个账号的所属分类
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    $tmp = fetch_array("SELECT t.* FROM other_type wt"
                            . " LEFT JOIN type t ON  wt.type_id = t.id "
                            . "WHERE wt.other_id = " . $v["id"]);
                    $tmp_type = array();
                    foreach ($tmp as $vv) {
                        $tmp_type[] = $vv["type_name"];
                    }
                    $res[$k]["type_name"] = implode("|", $tmp_type);
                }
            }
            $data['res'] = $res;
            $this->pagination->initialize($config);
            $page = $this->pagination->create_links();
            $data['pager'] = $page;
            $this->load->view('other_list', $data);
        }
        /////////////////导出动作///////////////////////////////////
        else {
            $res = fetch_array($sql . " ORDER BY edittime ASC");
            $data['count'] = fetch_count($sql);
            //获取每个账号的所属分类
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    $tmp = fetch_array("SELECT t.* FROM other_type wt"
                            . " LEFT JOIN type t ON  wt.type_id = t.id "
                            . "WHERE wt.other_id = " . $v["id"]);
                    $tmp_type = array();
                    foreach ($tmp as $vv) {
                        $tmp_type[] = $vv["type_name"];
                    }
                    $res[$k]["type_name"] = implode("|", $tmp_type);
                }
            }
            $data['res'] = $res;
            $content = $this->load->view('other_export', $data, true);
            
            user_log_save($_SESSION["username"],$_SESSION["userid"],"导出".$data['count']."个其他账号");
            
            header("Content-type:application/vnd.ms-excel;charset:utf8");
            header("Content-Disposition:filename=" . "other" . date("YmdHis") . ".xls");
            echo $content;
        }
    }

    public function other_add() {
        $data['menu'] = "manage_other";
        $data['type_list'] = fetch_array("select * from type");
        $this->load->view('other_add', $data);
    } 

    public function other_edit() {
        $data['menu'] = "manage_other";
        $id = getGP('id');
        $sql = "select * from other where id='" . $id . "'";
        $res = fetch_one_array($sql);
        //获取该账号所属类别
        $tmp = fetch_array("SELECT t.* FROM other_type wt"
                . " LEFT JOIN type t ON  wt.type_id = t.id "
                . "WHERE wt.other_id = " . $res["id"]);
        if (!empty($tmp)) {
            foreach ($tmp as $vv) {
                $res["type_ids"][] = $vv["id"];
            }
        } else {
            $res["type_ids"] = array();
        }
        $data['res'] = $res;

        $data['type_list'] = fetch_array("select * from type");
        $this->load->view('other_edit', $data);
    }

    public function other_save() {
        $data['menu'] = "manage_other";
        $ins_data['account_name'] = getGP('account_name');
        $ins_data['description'] = getGP('description');
        $ins_data['ps'] = getGP('ps');
        $ins_data['display_order'] = getGP('display_order');
        // shuai180806
        $ins_data['address'] = getGP('address');//地址
        $ins_data['case'] = getGP('case');//案例
        $ins_data['original_price'] = getGP('original_price');//原创直发
        $ins_data['contact'] = getGP('contact');//联系方式
        $ins_data['id'] = getGP('id');
        $type_ids = $_POST['type_ids'];

        //图片上传
        $config['upload_path']='./uploads/';
        $config['allowed_types']='gif|jpg|png';
        $config['max_size']=5120;
        $config['encrypt_name']=true;
        $file_name = null;
        $this->load->library('upload',$config);
        if(!$this->upload->do_upload('head_img')){
            $error=array('error'=>$this->upload->display_errors());
            var_dump($error);
            if(!empty($ins_data['id'])){//说明是修改资料
                var_dump("有id是".$ins_data['id']);   
                $query = $this->db->query('SELECT head_img FROM other WHERE id = '.$ins_data['id']);
                $ins_data['head_img'] = $query->result()[0]->head_img;
            }else{ 
                alert("头像上传失败,图片（gif/jpg/png）不要超过5M");
            } 
        }else{
            $data=array('upload_data'=>$this->upload->data());
            $file_name = $data["upload_data"]["file_name"];
            $ins_data['head_img'] = "http://".$_SERVER['SERVER_NAME']."/uploads/".$file_name;
        }




        if (empty($type_ids)) {
            alert("请选择所属类别");
        }

        $id = 0;

        if (!empty($ins_data['id'])) {
            $ins_data["edittime"] = time();
            $r = $this->db->update('other', $ins_data, "id =" . $ins_data['id']);
            $id = $ins_data['id'];
        } else {
            $ins_data["addtime"] = time();
            $ins_data["edittime"] = time();
            $this->db->insert('other', $ins_data);
            $id = $this->db->insert_id();
        }

        if (!empty($id)) {
            //修改所属类别
            //先删除
            $sql = "delete from other_type where other_id='" . $id . "'";
            $r = $this->db->query($sql);
            foreach ($type_ids as $type_id) {
                $this->db->insert("other_type", array("other_id" => $id, "type_id" => $type_id));
            }
            user_log_save($_SESSION["username"],$_SESSION["userid"],"新增或编辑其他账号\"".$ins_data['account_name']."\"");
            alert("保存成功", "index.php?c=manage&m=other_list");
        } else {
            alert("保存失败");
        }
    }

    public function other_delete() {
        $data['menu'] = "manage_other";
        $id = intval(getGP('id'));
        $del_ids = getGP("del_ids");  
        if(empty($id)&&empty($del_ids)){
            alert("缺少ID", "index.php?c=manage&m=other_list");
        }
        $ids_string = !empty($del_ids)?$del_ids:$id;

        $sql = "delete from other where id IN(" . $ids_string . ")";
        $r = $this->db->query($sql);
        $sql = "delete from other_type where other_id IN(" . $ids_string . ")";
        $r = $this->db->query($sql);

        if ($r) {
            user_log_save($_SESSION["username"],$_SESSION["userid"],"删除了id为".$ids_string."账号");
            alert("删除成功", "index.php?c=manage&m=other_list");
        } else {
            alert("删除失败", "index.php?c=manage&m=other_list");
        }
    }

    //其他导入
    public function other_import() {
        ini_set('max_execution_time', '0');
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'csv|txt';
        $config['max_size'] = '1000000';
        $this->load->library('upload', $config);
        if (empty($_FILES["userfile"]["tmp_name"])) {
            alert("请选择上传的文件");
        }
        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            alert($error["error"]);
            die;
        } else {
            $data = array('upload_data' => $this->upload->data());

            //先读取内容并转成UTF-8编码，再重新写入
            file_put_contents($data['upload_data']['full_path'], mb_convert_encoding(file_get_contents($data['upload_data']['full_path']), "UTF-8", "GBK"));
            //重新用fgetcsv读取csv内容
            $h = fopen($data['upload_data']['full_path'], "r");
            $i = 0;
            $count=0;
            while ($tmp = _fgetcsv($h)) {
                $i++;
                if ($i == 1) {
                    continue;
                }

                if (!empty($tmp[0])) {
                    $ins_data['account_name'] = $tmp[1];
                    $ins_data['description'] = $tmp[2];
                    $ins_data['address'] = $tmp[3];
                    $ins_data['case'] = $tmp[4];
                    $ins_data['original_price'] = $tmp[5];
                    $ins_data['ps'] = $tmp[6];
                    $ins_data['contact'] = $tmp[7];


                    $ins_data["addtime"] = time();
                    $ins_data["edittime"] = time();
                    $this->db->insert('other', $ins_data);
                    $other_id = $this->db->insert_id();
                    if (!empty($other_id)) {
                        $count++;
                        if (!empty($tmp[0])) {
                            $types = explode("|", $tmp[0]);
                            foreach ($types as $type) {
                                $type_data = fetch_one_array("SELECT * FROM type WHERE type_name='" . $type . "'");
                                if (empty($type_data)) {
                                    $type_id = $this->db->insert('type', array("type_name" => $type));
                                } else {
                                    $type_id = $type_data['id'];
                                }
                                $this->db->insert("other_type", array("other_id" => $other_id, "type_id" => $type_id));
                            }
                        }
                    } else {
                        alert("第" . $i . "条数据添加失败,请检查后重新导入");
                        break;
                    }
                }
            }
            user_log_save($_SESSION["username"],$_SESSION["userid"],"导入文件，共添加了".$count."个其他账号");
            alert("导入成功！","index.php?c=manage&m=other_list");
        }
    }


    /*     * ***************************************分类管理********************************************************** */

    public function type_list() {
        $data['menu'] = "manage_type";

        $per_page = getGP('per_page') ? getGP('per_page') : 1;
        $start = ($per_page - 1) * $this->pagination->per_page;
        $limit = $this->pagination->per_page;

        $keyword = getGP('keyword');
        $data['keyword'] = $keyword;
        $where = " where 1 ";
        if ($data['keyword']) {
            $where .=" and ( type_name like '%$keyword%')";
        }
        $sql = "select * from type $where ";
//        $count = fetch_count($sql);
//        $res = fetch_array($sql . " order by id DESC  LIMIT $start,$limit");
        $res = fetch_array($sql);
        $data['res'] = $res;

//        $config['total_rows'] = $count;
//        $config['base_url'] = "index.php?c=manage&m=type_list";
//        $this->pagination->initialize($config);
//        $page = $this->pagination->create_links();
//        $data['pager'] = $page;

        $this->load->view('type_list', $data);
    }

    public function type_add() {
        $data['menu'] = "manage_type";
        $this->load->view('type_add', $data);
    } 

    public function type_edit() { 
        $data['menu'] = "manage_type";
        $id = getGP('id');
        $sql = "select * from type where id='" . $id . "'";
        $res = fetch_one_array($sql);
        $data['res'] = $res;
        $this->load->view('type_edit', $data);
    }

    public function type_save() { 
        $data['menu'] = "manage_type";
        $ins_data['type_name'] = getGP('type_name');
        $ins_data['id'] = getGP('id');

//        if (empty($ins_data['username'])) {
//            alert("请输入姓名：");
//        }
        if (!empty($ins_data['id'])) {
            $r = $this->db->update('type', $ins_data, "id =" . $ins_data['id']);
        } else {
            $this->db->insert('type', $ins_data);
            $r = $this->db->insert_id();
        }

        if ($r) {
            alert("保存成功", "index.php?c=manage&m=type_list");
        } else {
            alert("保存失败");
        }
    }

    public function type_delete() {
        $data['menu'] = "manage_type";
        $id = intval(getGP('id'));
        if (empty($id)) {
            alert("缺少ID");
        }
        $sql = "delete from type where id='" . $id . "'";
        $r = $this->db->query($sql);
        if ($r) {
            alert("删除成功", "index.php?c=manage&m=type_list");
            
        } else {
            alert("删除失败");
        }
    }

    
}
function _fgetcsv(& $handle, $length = null, $d = ',', $e = '"') {
     $d = preg_quote($d);
     $e = preg_quote($e);
     $_line = "";
     $eof=false;
     while ($eof != true) {
         $_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
         $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
         if ($itemcnt % 2 == 0)
             $eof = true;
     }
     $_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
     $_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
     preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
     $_csv_data = $_csv_matches[1];
     for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
         $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1' , $_csv_data[$_csv_i]);
         $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
     }
     return empty ($_line) ? false : $_csv_data;
}